package com.lepu.app.fun.grow.fragment;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.config.UserConfig;
import com.app.utils.AppEnterTongJi;
import com.app.utils.Const;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragment;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.core.BitmapManager;
import com.core.lib.core.HttpRequest;
import com.core.lib.ui.wheel.NumericWheelAdapter;
import com.core.lib.ui.wheel.OnWheelChangedListener;
import com.core.lib.ui.wheel.WheelView;
import com.core.lib.utils.CallBack;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.utils.ImageCompressUtils;
import com.core.lib.utils.PopUtil;
import com.core.lib.utils.geneal.UploadMenuImage;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.ImageUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.utils.photo.AppPhotoGridActivity;
import com.core.lib.utils.photo.PhotoInfo;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.core.lib.utils.secure.EncodeMD5;
import com.core.lib.widget.CircularImageView;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.grow.GrowApplyPhotoActivity;
import com.lepu.app.fun.grow.GrowMedalWallActivity;
import com.lepu.app.fun.grow.GrowSavePhotoManager;
import com.lepu.app.fun.grow.adapter.PhotoItemAdapter;
import com.lepu.app.fun.grow.bean.PhotoItem;
import com.lepu.app.fun.grow.bean.PhotoItemNet;
import com.lepu.app.fun.grow.calendar.GrowCalendarActivity;
import com.lepu.app.fun.grow.play.PlayImageAutoActivity;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.main.permission.PermissionUtil;
import com.lepu.app.main.permission.callback.PermissionResultCallBack;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.ListViewForScrollview;

public class FragmentGrow extends BaseFragment implements AsyncRequest {

	private static final String REQUEST_SAVE_ALBUM_NAME = "request_save_album_name";
	private static final String REQUEST_FIRST_SYNC_DATA = "request_first_sync_data";
	private static final String REQUEST_DOWNLOAD_DATA = "request_download_data";
	private static final String REQUEST_UPLOAD_DATA = "request_upload_data";

	private static final int MSG_FIRST_SYNC_DATA = 10;
	private static final int MSG_SYNC_DATA = 20;
	public static final int MSG_UPLOAD_DATA = 21;
	public static final int MSG_SAVE_UPLOAD_SUCCESS = 22;

	public static final int MSG_UPDATE_ALBUM_COVER = 30;

	public static final int PHOTO_COUNT_MAX = 9;

	private static final int JUMP_CALENDAR_REQUEST_CODE = 100;

	private static FragmentGrow mFragmentInstance = null;
	private View mMainView = null;

	public String mCurrentDateString = "";

	private ListViewForScrollview mDataListView;
	private PhotoItemAdapter mDataAdapter;
	private ArrayList<PhotoItem> mDataList = new ArrayList<PhotoItem>();
	private boolean mInitDataSuccess = false;

	private ScrollView mScrollView;
	// private TextView mCurrentDateDayTextView1;
	// private TextView mCurrentDateDayTextView2;

	public ImageView mModifyImageView;
	public PhotoItem mModifyPhotoItem;

	private LinearLayout mBeforeDayLayout;
	private LinearLayout mLaterDayLayout;
	private TextView mCenterTitleDateTextView;
	private TextView mAddPhotoTextView;

	// download
	public boolean mFirstSyncData = true;
	private ArrayList<PhotoItemNet> mPhotoItemNetList = null;
	private int mDownloadImageFlag = 0;

	// upload
	public boolean mIsUpdate = false;
	public boolean mCloudLocal = false;
	private MyDialog mFirstSyncDialog = null;
	private TextView mUpdateMessageTextView;

	private MyDialog mCancelDialog = null;

	public static FragmentGrow getInstance() {
		return mFragmentInstance;
	}

	@SuppressLint("InflateParams")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mMainView = LayoutInflater.from(getActivity()).inflate(
				R.layout.grow_fragment_grow, null, false);
		mFragmentInstance = this;

		init();
	}

	@Override
	public void onResume() {
		super.onResume();

		if (mInitDataSuccess) {
			if (MyApplication.getInstance().checkIsLogin()) {
				// test
				// updateData(false);

				// 添加照片
				updateAddImages();
			} else {
				clearDataList();
			}
			updateLoginInfo();

			requestFirstSyncData();
			
			UmengHelper.OnPageStart("23");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		ViewGroup p = (ViewGroup) mMainView.getParent();
		if (p != null) {
			p.removeAllViewsInLayout();
		}
		return mMainView;
	}

	@Override
	public void onPause() {
		super.onPause();

		// 保存相册名字
		saveAlbumName();
		/**
		 * 播放图片时候有的照片描述没有显示出来，是因为没保存，因为onPause方法是activity的方法，当前Fragment退出后，
		 * Activity并没有退出，所以没保存， 应该是Fragment退出就保存，就可以了。
		 */

		// Log.i("hz","mDataList:"+mDataList.size());
		// 保存数据
		saveImageData();
		UmengHelper.OnPageEnd("23");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		mInitDataSuccess = false;
		mFragmentInstance = null;

		LogUtilBase.LogD(null, "FragmentGrow onDestroy");
		/*
		 * 退出了
		 */
		updateQuit();
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);

		if (isVisibleToUser) {
			if (!mInitDataSuccess) {
				mInitDataSuccess = true;
				updateData(true);
			}
		}
	}

	public void requestFirstSyncData() {
		if (MyApplication.getInstance().checkIsLogin() && !mIsUpdate) {
			int currentIndex = MainTabActivity.getInstance()
					.getMainMenuSelected();
			if (currentIndex != 2)
				return;

			// 第一次请求同步数据
			boolean flag = UserConfig.getConfigBoolean(getActivity(),
					Const.CONFIG_APP_FIRST_SYNC_DATA, true);
			String cancelFlag = UserConfig.getConfigString(getActivity(),
					Const.CONFIG_APP_FIRST_SYNC_DATA_CANCEL_INDEX, "");
			boolean noNotifyFlag = UserConfig.getConfigBoolean(getActivity(),
					Const.CONFIG_APP_FIRST_SYNC_DATA_NO_NOTIFY, false);

			int count = PhotoItem.getAllPhotoCount(MyApplication.getInstance()
					.getLoginInfo().UserID);
			boolean ifData = count == 0 ? true : false;

			// 第一次进入程序，或者有被中途取消下载的记录，
			if (ifData && !noNotifyFlag && (flag || !TextUtils.isEmpty(cancelFlag))
					&& mFirstSyncData) {

				requestSyncAllData();
			}
		}
	}

	private void updateAddImages() {
		if (AppPhotoGridActivity.mSelectList.size() > 0) {

			dynamicUpdateAlbumCover();
			for (PhotoInfo item : AppPhotoGridActivity.mSelectList) {

				String tempPath = item.getPath_absolute();

				try {
					addPhotoItem(tempPath, false);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
			PopUtil.getInstance().dismissPopWindow();

			updateData(true);
			updateAddPhotoTextView();
		}

		if (AppPhotoGridActivity.mSelectList != null) {
			AppPhotoGridActivity.mSelectList.clear();
		}
	}

	public void updateData(boolean needProgress) {
		// 获取数据
		if (MyApplication.getInstance().checkIsLogin()) {
			if (needProgress) {
				MainTabActivity.getInstance().showProgressDialog();
			}

			new PhotoAsyncTask().execute();
		}
	}

	private void saveAlbumName() {
		EditText albumNameEditText = (EditText) mMainView
				.findViewById(R.id.albumNameEditText);
		String albumName = albumNameEditText.getText().toString().trim();

		String saveAlbumName = UserConfig.getConfigString(getActivity(),
				Const.CONFIG_APP_ALBUM_NAME, "");
		if (TextUtils.isEmpty(saveAlbumName) && !TextUtils.isEmpty(albumName)) {
			UserConfig.setConfig(getActivity(), Const.CONFIG_APP_ALBUM_NAME,
					albumName);

			if (MyApplication.getInstance().checkIsLogin()) {
				LoginInfo loginInfo = MyApplication.getInstance()
						.getLoginInfo();
				String url = Setting.getModiyAlbumNameUrl();

				Map<String, Object> map = new HashMap<String, Object>();
				JSONObject params = new JSONObject();
				try {
					params.put("DeviceID", Setting.DEVICEID);
					params.put("ApplicationID", Setting.APPLICATIONID);
					params.put("UserID", loginInfo.UserID);
					params.put("LoginToken", loginInfo.LoginToken);

					params.put("AlbumName", albumName);
				} catch (Exception e) {
				}
				map.put("ht", params);

				ApiClient.http_post_main(url, map, null, this,
						REQUEST_SAVE_ALBUM_NAME, false);
			}
		}
	}

	private void init() {

		mCurrentDateString = DateUtilBase.stringFromDate(new Date(),
				DateUtilBase.YEAR_MONTH_DAY);

		LinearLayout noLoginLayout = (LinearLayout) mMainView
				.findViewById(R.id.noLoginLayout);
		// LinearLayout yesLoginLayout = (LinearLayout) mMainView
		// .findViewById(R.id.yesLoginLayout);

		LinearLayout bottomAddPhotoLayout = (LinearLayout) mMainView
				.findViewById(R.id.bottomAddPhotoLayout);
		Button bottomMenuSeeButton = (Button) mMainView
				.findViewById(R.id.bottomMenuSeeButton);
		Button bottomMenuApplyPhotoButton = (Button) mMainView
				.findViewById(R.id.bottomMenuApplyPhotoButton);
		Button bottomMenuSavePhotoButton = (Button) mMainView
				.findViewById(R.id.bottomMenuSavePhotoButton);

		noLoginLayout.setOnClickListener(mViewClickListener);
		// yesLoginLayout.setOnClickListener(mViewClickListener);
		bottomAddPhotoLayout.setOnClickListener(mViewClickListener);
		bottomMenuSeeButton.setOnClickListener(mViewClickListener);
		bottomMenuApplyPhotoButton.setOnClickListener(mViewClickListener);
		bottomMenuSavePhotoButton.setOnClickListener(mViewClickListener);

		mDataListView = (ListViewForScrollview) mMainView
				.findViewById(R.id.centerPhotoListView);

		mScrollView = (ScrollView) mMainView.findViewById(R.id.scrollView);
		mScrollView.setOnTouchListener(new OnTouchListener() {
			
			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				UtilityBase.closeSoftInput(getActivity());
				return false;
			}
		});

		ImageView albumPlayImageView = (ImageView) mMainView
				.findViewById(R.id.albumPlayImageView);
		albumPlayImageView.setOnClickListener(mViewClickListener);

		EditText albumNameEditText = (EditText) mMainView
				.findViewById(R.id.albumNameEditText);
		albumNameEditText.setFilters(new InputFilter[] { new EmojiFilter(),
				new InputFilter.LengthFilter(20) });

		mAddPhotoTextView = (TextView) mMainView
				.findViewById(R.id.addPhotoTextView);
		mBeforeDayLayout = (LinearLayout) mMainView
				.findViewById(R.id.beforeDayLayout);
		mLaterDayLayout = (LinearLayout) mMainView
				.findViewById(R.id.laterDayLayout);
		mCenterTitleDateTextView = (TextView) mMainView
				.findViewById(R.id.centerTitleDateTextView);
		LinearLayout centerTitleDateLayout = (LinearLayout) mMainView
				.findViewById(R.id.centerTitleDateLayout);

		mBeforeDayLayout.setOnClickListener(mViewClickListener);
		mLaterDayLayout.setOnClickListener(mViewClickListener);
		centerTitleDateLayout.setOnClickListener(mViewClickListener);

		mCenterTitleDateTextView.setText(DateUtilBase.stringFromDate(
				new Date(), "yyyy年MM月dd日"));
		mLaterDayLayout.setVisibility(View.GONE);

		updateAlbumCover();
		updateLoginInfo();

		mScrollView.smoothScrollTo(0, 0);
	}

	/*
	 * 登录状态变更，需要执行这个方法
	 */
	public void updateLoginInfo() {
		LinearLayout yesLoginLayout = (LinearLayout) mMainView
				.findViewById(R.id.yesLoginLayout);
		LinearLayout noLoginLayout = (LinearLayout) mMainView
				.findViewById(R.id.noLoginLayout);

		CircularImageView accountIconImageView = (CircularImageView) mMainView
				.findViewById(R.id.accountIconImageView);
		if (MyApplication.getInstance().checkIsLogin()) {
			yesLoginLayout.setVisibility(View.VISIBLE);
			noLoginLayout.setVisibility(View.GONE);

			// update user info
			TextView nameTextView = (TextView) mMainView
					.findViewById(R.id.nameTextView);
			nameTextView
					.setText(MyApplication.getInstance().getLoginInfo().NickName);

			accountIconImageView
					.setImageResource(R.drawable.app_ic_default_avatar);

			LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
			if (!TextUtils.isEmpty(loginInfo.Avatar)) {
				String filePath = SdLocal.getUserPath(getActivity(),
						loginInfo.UserID);
				String imageUrl = Setting.getImageUrl(loginInfo.Avatar);

				BitmapManager.getInstance().loadBitmap(imageUrl, filePath,
						accountIconImageView, true);

				// MyApplication.disPlay(imageUrl, accountIconImageView,
				// R.drawable.default_icon_small);
			}

			// update medal
			updateMedalLayout();

			ProgressBar progressBar = (ProgressBar) mMainView
					.findViewById(R.id.progressBar);
			progressBar.setProgress(50);

			ImageView rightHelpImageView = (ImageView) mMainView
					.findViewById(R.id.rightHelpImageView);
			rightHelpImageView.setOnClickListener(mViewClickListener);

			updatePopSelectDateView();
		} else {
			yesLoginLayout.setVisibility(View.GONE);
			noLoginLayout.setVisibility(View.VISIBLE);

			LinearLayout bottomAddPhotoLayout = (LinearLayout) mMainView
					.findViewById(R.id.bottomAddPhotoLayout);
			bottomAddPhotoLayout.setVisibility(View.VISIBLE);
		}

		updateBottomMenu();

		// 是否播放示例相册
		updateAlbumContent();
		updateAlbumCoverText();

		updateAddPhotoTextView();
	}

	private void updateAddPhotoTextView() {
		if (mDataList != null && mDataList.size() > 0) {
			if (mDataList.size() >= PHOTO_COUNT_MAX) {
				mAddPhotoTextView.setText("每天只能添加9张照片");
			} else {
				mAddPhotoTextView.setText("继续添加");
			}
		} else {
			mAddPhotoTextView.setText("添加照片到相册");
		}
	}

	/*
	 * 再添加图片时，更新相册封面
	 */
	public void dynamicUpdateAlbumCover() {
		if (MyApplication.getInstance().checkIsLogin()) {

			LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();

			int count = PhotoItem.getAllPhotoCount(loginInfo.UserID);
			if (count == 0 && TextUtils.isEmpty(loginInfo.AlbumCoverURL)) {
				ImageView albumCoverImageView = (ImageView) mMainView
						.findViewById(R.id.albumCoverImageView);
				UniversalImageLoadTool.disPlayNoCache(ImageUtilBase
						.getDrawableImageUrl(R.drawable.album_cover_default),
						albumCoverImageView, R.drawable.album_cover_default);
			}
		}
	}

	/*
	 * 第一次进入时更新，或者登陆，登出时，别的地方调用更新
	 */
	public void updateAlbumCover() {

		UniversalImageLoadTool.clear();

		ImageView albumCoverImageView = (ImageView) mMainView
				.findViewById(R.id.albumCoverImageView);

		int width = UtilityBase.getWindowWidthHeight(getActivity())[0];
		LayoutParams params = albumCoverImageView.getLayoutParams();
		params.width = width;
		params.height = width * 9 / 16;
		albumCoverImageView.setLayoutParams(params);

		if (MyApplication.getInstance().checkIsLogin()) {
			LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
			String coverPath = SdLocal.getAlbumUserPath(getActivity(),
					loginInfo.UserID, "album_cover");

			if (new File(coverPath).exists()) {
				UniversalImageLoadTool.disPlayNoCache(ImageUtilBase.getFileImageUrl(coverPath), albumCoverImageView, R.drawable.album_cover_default);
			} else {
				int count = PhotoItem.getAllPhotoCount(loginInfo.UserID);
				if (count > 0) {
					UniversalImageLoadTool
							.disPlayNoCache(
									ImageUtilBase
											.getDrawableImageUrl(R.drawable.album_cover_default),
									albumCoverImageView,
									R.drawable.album_cover_default);
				} else {
					UniversalImageLoadTool.disPlayNoCache(ImageUtilBase
							.getDrawableImageUrl(R.drawable.grow_xiangkuang),
							albumCoverImageView, R.drawable.grow_xiangkuang);
				}
			}

		} else {
			UniversalImageLoadTool.disPlayNoCache(ImageUtilBase
					.getDrawableImageUrl(R.drawable.grow_xiangkuang),
					albumCoverImageView, R.drawable.grow_xiangkuang);
		}

	}

	private void updateAlbumCoverText() {
		TextView albumCoverTextView = (TextView) mMainView
				.findViewById(R.id.albumCoverTextView);

		if (MyApplication.getInstance().checkIsLogin()) {
			LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();

			int count = PhotoItem.getAllPhotoCount(loginInfo.UserID);
			if (count > 0) {
				albumCoverTextView.setVisibility(View.VISIBLE);
				albumCoverTextView.setText(String.format("已添加%d张照片", count));
			} else {
				albumCoverTextView.setVisibility(View.GONE);
			}
		} else {
			albumCoverTextView.setVisibility(View.GONE);
		}
	}

	private void updateBottomMenu() {
		LinearLayout bottomMenuLayout = (LinearLayout) mMainView
				.findViewById(R.id.bottomMenuLayout);
		EditText albumNameEditText = (EditText) mMainView
				.findViewById(R.id.albumNameEditText);

		if (mDataList != null && mDataList.size() > 0) {
			bottomMenuLayout.setVisibility(View.VISIBLE);

			String albumName = UserConfig.getConfigString(getActivity(),
					Const.CONFIG_APP_ALBUM_NAME, "");
			if (TextUtils.isEmpty(albumName)) {
				albumNameEditText.setVisibility(View.VISIBLE);
			} else {
				albumNameEditText.setVisibility(View.GONE);
			}

			Button bottomMenuApplyPhotoButton = (Button) mMainView
					.findViewById(R.id.bottomMenuApplyPhotoButton);
			Button bottomMenuSavePhotoButton = (Button) mMainView
					.findViewById(R.id.bottomMenuSavePhotoButton);

			String uid = MyApplication.getInstance().getLoginInfo().UserID;
			int count = PhotoItem.getPhotosByDateNoUpdateCount(uid,
					mCurrentDateString);
			if (count > 0) {
				bottomMenuApplyPhotoButton.setVisibility(View.GONE);
				bottomMenuSavePhotoButton.setVisibility(View.VISIBLE);
			} else {
				bottomMenuApplyPhotoButton.setVisibility(View.VISIBLE);
				bottomMenuSavePhotoButton.setVisibility(View.GONE);
			}

			boolean flag = UserConfig.getConfigBoolean(
					MyApplication.getInstance(), mCurrentDateString, false);
			if (flag) {
				bottomMenuApplyPhotoButton.setText("重新申请热门相册");
			} else {
				bottomMenuApplyPhotoButton.setText("申请热门相册");
			}
		} else {
			bottomMenuLayout.setVisibility(View.GONE);
			albumNameEditText.setVisibility(View.GONE);
		}
	}

	/*
	 * 更新勋章
	 */
	private void updateMedalLayout() {
		// LinearLayout medalContainerlayout = (LinearLayout)
		// mMainView.findViewById(R.id.medalContainerlayout);
	}

	/*
	 * 更新相册该播放什么内容
	 */
	private void updateAlbumContent() {
		TextView albumDefaultNameTextView = (TextView) mMainView
				.findViewById(R.id.albumDefaultNameTextView);

		String albumName = UserConfig.getConfigString(getActivity(),
				Const.CONFIG_APP_ALBUM_NAME, Const.DEFAULT_CUSTOM_ALBUM_NAME);
		albumDefaultNameTextView.setText(albumName);
	}

	/*
	 * 完善信息状态变更，需要执行这个方法 更新选择日期显示
	 */
	public void updatePopSelectDateView() {
		// LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
		// String birthDay = loginInfo.BabyBirthDate;
		// if (!TextUtils.isEmpty(birthDay) &&
		// loginInfo.BabyBirthed.equals("1")) {
		// int[] array = Utils.getCacuteTimeDayString(birthDay,
		// mCurrentDateString);
		// mCurrentDateDayTextView1.setText(String.valueOf(array[0]));
		// mCurrentDateDayTextView2.setText(String.valueOf(array[1]));
		// } else {
		// mCurrentDateDayTextView1.setText("0");
		// mCurrentDateDayTextView2.setText("0");
		// }
	}

	public void clearDataList() {
		if (mDataList != null && mDataList.size() > 0) {
			mDataList.clear();
			if (mDataAdapter != null) {
				mDataAdapter.notifyDataSetChanged();
			}
		}
	}

	private class PhotoAsyncTask extends AsyncTask<Void, Void, Object> {

		@Override
		protected Object doInBackground(Void... params) {

			mInitDataSuccess = true;
			mDataList = PhotoItem.getPhotosByDate(MyApplication.getInstance()
					.getLoginInfo().UserID + "", mCurrentDateString);

			if (mDataList == null) {
				mDataList = new ArrayList<PhotoItem>();
			} else {
				// 确保，本地数据库，与本地文件是否一致
				for (int i = 0; i < mDataList.size(); i++) {
					String filePath = mDataList.get(i).imagePath;
					File file = new File(filePath);
					if (!file.exists()) {
						mDataList.remove(i);
					}
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			
			MainTabActivity.getInstance().hideProgressDialog();

			updateAddPhotoTextView();

			// updateAlbumContent();
			updateAddPhotoTextView();

			updateBottomMenu();
			updateAlbumCoverText();

			mDataAdapter = new PhotoItemAdapter(getActivity(), mDataList);
			mDataListView.setAdapter(mDataAdapter);
		}
	}

	@SuppressLint("InflateParams")
	private void showPopSelectDate(View topView) {
		final View view = LayoutInflater.from(getActivity()).inflate(
				R.layout.grow_pop_main_select_date, null);

		// TextView wheelRightTextView = (Button)
		// view.findViewById(R.id.wheelRightTextView);
		Date date = DateUtilBase.dateFromString(mCurrentDateString,
				DateUtilBase.YEAR_MONTH_DAY);
		setDateTimePicker(date, view);
		PopUtil.getInstance().showPopWindow(getActivity(), topView, view, 0,
				new OnDismissListener() {

					@Override
					public void onDismiss() {
						// 如果是个数,则显示为"02"的样式
						WheelView wv_year = (WheelView) view
								.findViewById(R.id.yearWheel);
						WheelView wv_month = (WheelView) view
								.findViewById(R.id.monthWheel);
						WheelView wv_day = (WheelView) view
								.findViewById(R.id.dayWheel);

						String parten = "00";
						DecimalFormat decimal = new DecimalFormat(parten);
						// 设置日期的显示
						String text = (wv_year.getCurrentItem() + MyDialog.START_YEAR)
								+ "-"
								+ decimal.format((wv_month.getCurrentItem() + 1))
								+ "-"
								+ decimal.format((wv_day.getCurrentItem() + 1));
						long chooseTime = DateUtilBase.dateFromString(text,
								DateUtilBase.YEAR_MONTH_DAY).getTime();
						if (chooseTime > System.currentTimeMillis()) {
							UIHelper.showToast(getActivity(), "请不要选择当前以后的时间");

							Date currentDate = DateUtilBase.dateFromString(
									mCurrentDateString,
									DateUtilBase.YEAR_MONTH_DAY);
							mCenterTitleDateTextView.setText(DateUtilBase
									.stringFromDate(currentDate, "yyyy年MM月dd日"));

						} else {
							// 都是今天，就不筛选数据了
							if (!text.equals(mCurrentDateString)) {
								// 先保存当天的数据
								saveImageData();

								mCurrentDateString = text;
								updateData(true);
							}

							// Date date = DateUtilBase.dateFromString(text,
							// DateUtilBase.YEAR_MONTH_DAY);
							// long time = date.getTime() - birthday.getTime();
							// if (time <= 0) {
							// UIHelper.showToast(getActivity(),
							// "请不要选择生日以前的时间");
							//
							// // int[] array = Utils.getCacuteTimeDayString(
							// // MyApplication.getInstance()
							// // .getLoginInfo().BabyBirthDate,
							// // mCurrentDateString);
							// // mCurrentDateDayTextView1.setText(String
							// // .valueOf(array[0]));
							// // mCurrentDateDayTextView2.setText(String
							// // .valueOf(array[1]));
							// } else {
							// // 都是今天，就不筛选数据了
							// if (!text.equals(mCurrentDateString)) {
							// // 先保存当天的数据
							// saveImageData();
							//
							// mCurrentDateString = text;
							//
							// Date currentDate = DateUtilBase
							// .dateFromString(mCurrentDateString,
							// DateUtilBase.YEAR_MONTH_DAY);
							// mCenterTitleDateTextView
							// .setText(DateUtilBase
							// .stringFromDate(currentDate,
							// "yyyy年MM月dd日"));
							// updateData(true);
							// }
							// }
						}
					}
				}, true);
	}

	private void setDateTimePicker(Date date, final View view) {
		int year = 0;
		int month = 0;
		int day = 0;

		Calendar calendar = Calendar.getInstance();
		// int currentYear = calendar.get(Calendar.YEAR);

		int currentYear = MyDialog.END_YEAR;
		if (date != null)
			calendar.setTime(date);

		year = calendar.get(Calendar.YEAR);
		month = calendar.get(Calendar.MONTH);
		day = calendar.get(Calendar.DATE);

		// 添加大小月月份并将其转换为list,方便之后的判断
		String[] months_big = { "1", "3", "5", "7", "8", "10", "12" };
		String[] months_little = { "4", "6", "9", "11" };

		final List<String> list_big = Arrays.asList(months_big);
		final List<String> list_little = Arrays.asList(months_little);

		// 年
		final WheelView wv_year = (WheelView) view.findViewById(R.id.yearWheel);
		//wv_year.setItemColor("#ffffff");
		//wv_year.setItemCurrentColor("#ffffff");
		wv_year.setWheelBg(R.drawable.wheel_grow_bg);
		wv_year.setWheelMiddle(R.drawable.wheel_grow_middle);

		wv_year.setAdapter(new NumericWheelAdapter(MyDialog.START_YEAR,
				currentYear));// 设置"年"的显示数据
		wv_year.setCyclic(true);// 可循环滚动
		// wv_year.setLabel("年");// 添加文字
		wv_year.setCurrentItem(year - MyDialog.START_YEAR);// 初始化时显示的数据

		// 月
		final WheelView wv_month = (WheelView) view
				.findViewById(R.id.monthWheel);
		//wv_month.setItemColor("#ffffff");
		//wv_month.setItemCurrentColor("#ffffff");
		wv_month.setWheelBg(R.drawable.wheel_grow_bg);
		wv_month.setWheelMiddle(R.drawable.wheel_grow_middle);

		wv_month.setAdapter(new NumericWheelAdapter(1, 12));
		wv_month.setCyclic(true);
		// wv_month.setLabel("月");
		wv_month.setCurrentItem(month);

		// 日
		final WheelView wv_day = (WheelView) view.findViewById(R.id.dayWheel);
		//wv_day.setItemColor("#ffffff");
		//wv_day.setItemCurrentColor("#ffffff");
		wv_day.setWheelBg(R.drawable.wheel_grow_bg);
		wv_day.setWheelMiddle(R.drawable.wheel_grow_middle);

		wv_day.setCyclic(true);
		// 判断大小月及是否闰年,用来确定"日"的数据
		if (list_big.contains(String.valueOf(month + 1))) {
			wv_day.setAdapter(new NumericWheelAdapter(1, 31));
		} else if (list_little.contains(String.valueOf(month + 1))) {
			wv_day.setAdapter(new NumericWheelAdapter(1, 30));
		} else {
			// 闰年
			if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
				wv_day.setAdapter(new NumericWheelAdapter(1, 29));
			else
				wv_day.setAdapter(new NumericWheelAdapter(1, 28));
		}
		// wv_day.setLabel("日");
		wv_day.setCurrentItem(day - 1);

		// 添加"年"监听
		OnWheelChangedListener wheelListener_year = new OnWheelChangedListener() {
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				int year_num = newValue + MyDialog.START_YEAR;
				// 判断大小月及是否闰年,用来确定"日"的数据
				if (list_big
						.contains(String.valueOf(wv_month.getCurrentItem() + 1))) {
					wv_day.setAdapter(new NumericWheelAdapter(1, 31));
				} else if (list_little.contains(String.valueOf(wv_month
						.getCurrentItem() + 1))) {
					wv_day.setAdapter(new NumericWheelAdapter(1, 30));
				} else {
					if ((year_num % 4 == 0 && year_num % 100 != 0)
							|| year_num % 400 == 0)
						wv_day.setAdapter(new NumericWheelAdapter(1, 29));
					else
						wv_day.setAdapter(new NumericWheelAdapter(1, 28));
				}

				// update top date
				updatePopTopDate(view);
			}
		};
		// 添加"月"监听
		OnWheelChangedListener wheelListener_month = new OnWheelChangedListener() {
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				int month_num = newValue + 1;
				// 判断大小月及是否闰年,用来确定"日"的数据
				if (list_big.contains(String.valueOf(month_num))) {
					wv_day.setAdapter(new NumericWheelAdapter(1, 31));
				} else if (list_little.contains(String.valueOf(month_num))) {
					wv_day.setAdapter(new NumericWheelAdapter(1, 30));
				} else {
					if (((wv_year.getCurrentItem() + MyDialog.START_YEAR) % 4 == 0 && (wv_year
							.getCurrentItem() + MyDialog.START_YEAR) % 100 != 0)
							|| (wv_year.getCurrentItem() + MyDialog.START_YEAR) % 400 == 0)
						wv_day.setAdapter(new NumericWheelAdapter(1, 29));
					else
						wv_day.setAdapter(new NumericWheelAdapter(1, 28));
				}

				// update top date
				updatePopTopDate(view);
			}
		};

		// 添加"天"监听
		OnWheelChangedListener wheelListener_day = new OnWheelChangedListener() {
			public void onChanged(WheelView wheel, int oldValue, int newValue) {

				// update top date
				updatePopTopDate(view);
			}
		};

		wv_year.addChangingListener(wheelListener_year);
		wv_month.addChangingListener(wheelListener_month);
		wv_day.addChangingListener(wheelListener_day);

		// 根据屏幕密度来指定选择器字体的大小
		int textSize = UtilityBase.getTextNumberSize(getActivity());

		wv_day.TEXT_SIZE = textSize;
		wv_month.TEXT_SIZE = textSize;
		wv_year.TEXT_SIZE = textSize;
	}

	private void updatePopTopDate(View view) {
		// 如果是个数,则显示为"02"的样式
		WheelView wv_year = (WheelView) view.findViewById(R.id.yearWheel);
		WheelView wv_month = (WheelView) view.findViewById(R.id.monthWheel);
		WheelView wv_day = (WheelView) view.findViewById(R.id.dayWheel);

		String parten = "00";
		DecimalFormat decimal = new DecimalFormat(parten);
		// 设置日期的显示
		String text = (wv_year.getCurrentItem() + MyDialog.START_YEAR) + "-"
				+ decimal.format((wv_month.getCurrentItem() + 1)) + "-"
				+ decimal.format((wv_day.getCurrentItem() + 1));

		Date currentDate = DateUtilBase.dateFromString(text,
				DateUtilBase.YEAR_MONTH_DAY);
		mCenterTitleDateTextView.setText(DateUtilBase.stringFromDate(
				currentDate, "yyyy年MM月dd日"));

		updateLaterDayVisible(text);
	}

	@SuppressLint("InflateParams")
	private void showPopTopHelp() {
		View view = LayoutInflater.from(getActivity()).inflate(
				R.layout.grow_pop_fragment1_top_help, null);

		ImageView rightHelpImageView = (ImageView) mMainView
				.findViewById(R.id.rightHelpImageView);
		PopUtil.getInstance().showPopWindow(getActivity(), rightHelpImageView,
				view, 0, null, true);
	}

	private View.OnClickListener mViewClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			int rid = v.getId();
			switch (rid) {
			case R.id.rightHelpImageView:

				// top right help
				showPopTopHelp();

				break;
			case R.id.noLoginLayout:

				MainTabActivity.jumpLogin(MainTabActivity.getInstance());
				break;
			case R.id.yesLoginLayout:
				Intent medalIntent = new Intent(getActivity(),
						GrowMedalWallActivity.class);
				MainTabActivity.getInstance().startActivity(medalIntent, true);
				break;
			case R.id.albumPlayImageView:

				AppEnterTongJi.clickEvent(62, "");
				
				Intent autoPlayIntent = new Intent(getActivity(),
						PlayImageAutoActivity.class);

				if (MyApplication.getInstance().checkIsLogin()) {
					LoginInfo loginInfo = MyApplication.getInstance()
							.getLoginInfo();
					int count = PhotoItem.getAllPhotosCount(loginInfo.UserID);
					if (count > 0) {
						// 播放自己的相册
						autoPlayIntent.putExtra("boolean_sample", false);
						autoPlayIntent.putExtra("boolean_all", true);// 播放当天的
						
					} else {
						// 播放示例相册
						autoPlayIntent.putExtra("boolean_sample", true);
					}
				} else {
					// 播放示例相册
					autoPlayIntent.putExtra("boolean_sample", true);
				}

				MainTabActivity.getInstance().startActivity(autoPlayIntent,
						true);
				break;
			case R.id.bottomAddPhotoLayout:

				AppEnterTongJi.clickEvent(65, "");
				
				// 检查是否登录，是否完善了信息
				boolean flag2 = MainTabActivity.jumpLogin(MainTabActivity
						.getInstance());
				if (flag2) {
					// 已经跳到登录页面
					return;
				}

				if (mDataList != null && mDataList.size() >= 9) {
					new MyDialog(getActivity())
							.setNegativeButtonSplitImageHide(true)
							.setMessage("您可以选择其他日期添加照片，已添加的照片都已保存在成长喜悦相册中")
							.setPositiveButton(R.string.app_ok,
									new View.OnClickListener() {

										@Override
										public void onClick(View v) {

										}
									}).create(null).show();

					return;
				}

				mModifyImageView = null;
				mModifyPhotoItem = null;
				// add photo pop
				showPopAddPhoto();
				
				break;
			case R.id.bottomMenuSeeButton:

				Intent playIntent = new Intent(getActivity(),
						PlayImageAutoActivity.class);
				if (mDataList != null && mDataList.size() > 0) {
					// 播放自己的相册
					playIntent.putExtra("boolean_sample", false);
					playIntent.putExtra("boolean_all", false);// 播放当天的
					playIntent.putExtra("current_day", mCurrentDateString);
					MainTabActivity.getInstance().startActivity(playIntent,
							true);
				} else {
					// 播放示例相册
					UIHelper.showToast(getActivity(), "请先添加照片");
				}

				break;
			case R.id.bottomMenuApplyPhotoButton:

				if (mDataList != null && mDataList.size() >= 3) {
					// LoginInfo loginInfo = MyApplication.getInstance()
					// .getLoginInfo();
					// int count = PhotoItem.getPhotosByDateNoUpdateCount(
					// loginInfo.UserID, mCurrentDateString);
					//
					// if (count > 0) {
					// Intent applyIntent = new Intent(getActivity(),
					// GrowApplyPhotoActivity.class);
					// applyIntent.putExtra("CurrentDateString",
					// mCurrentDateString);
					// MainTabActivity.getInstance().startActivity(
					// applyIntent, true);
					// } else {
					// UIHelper.showToast(getActivity(),
					// "您已申请过这一天的热门相册，请不要重复申请");
					// }
					Intent applyIntent = new Intent(getActivity(),
							GrowApplyPhotoActivity.class);
					applyIntent.putExtra("CurrentDateString",
							mCurrentDateString);
					MainTabActivity.getInstance().startActivity(applyIntent,
							true);

				} else {
					UIHelper.showToast(getActivity(), "至少添加3张照片,才可以申请热门相册");
				}

				break;
			case R.id.bottomMenuSavePhotoButton:

				saveImageData();
				requestUpload();

				// todo
				break;
			case R.id.beforeDayLayout:

				AppEnterTongJi.clickEvent(63, "");
				
				// 检查是否登录
				boolean loginFlag = MainTabActivity.jumpLogin(MainTabActivity
						.getInstance());

				if (loginFlag) {
					return;
				}

				saveImageData();

				updateDayData(0);
				
				break;
			case R.id.laterDayLayout:

				AppEnterTongJi.clickEvent(63, "");
				// 检查是否登录
				boolean loginFlag2 = MainTabActivity.jumpLogin(MainTabActivity
						.getInstance());

				if (loginFlag2) {
					return;
				}

				saveImageData();

				updateDayData(1);
				
				break;
			case R.id.centerTitleDateLayout:

				AppEnterTongJi.clickEvent(64, "");
				
				// 检查是否登录
				boolean loginFlag3 = MainTabActivity.jumpLogin(MainTabActivity
						.getInstance());

				if (loginFlag3) {
					return;
				}

				saveImageData();

				//
				// final LinearLayout topLayout = (LinearLayout) mMainView
				// .findViewById(R.id.topLayout);
				// // select date pop
				// new Handler().post(new Runnable() {
				// @Override
				// public void run() {
				// mScrollView.scrollTo(0, topLayout.getHeight());
				// }
				// });
				// showPopSelectDate(v);

				// todo
				Intent intent = new Intent(getActivity(),
						GrowCalendarActivity.class);
				startActivityForResult(intent, JUMP_CALENDAR_REQUEST_CODE);
				
				break;

			default:
				break;
			}
		}
	};

	private void updateLaterDayVisible(String dateString) {

		Date currentDate = DateUtilBase.dateFromString(dateString,
				DateUtilBase.YEAR_MONTH_DAY);
		String systemString = DateUtilBase.stringFromDate(new Date(),
				DateUtilBase.YEAR_MONTH_DAY);
		Date systemDate = DateUtilBase.dateFromString(systemString,
				DateUtilBase.YEAR_MONTH_DAY);

		if (currentDate.getTime() >= systemDate.getTime()) {
			mLaterDayLayout.setVisibility(View.GONE);
		} else {
			mLaterDayLayout.setVisibility(View.VISIBLE);
		}
	}

	private void updateDayData(int tag) {

		Date currentDate = DateUtilBase.dateFromString(mCurrentDateString,
				DateUtilBase.YEAR_MONTH_DAY);
		if (tag == 0) {
			// 前一天
			Date beforeDate = DateUtilBase.addDateOfDay(currentDate, -1);
			mCurrentDateString = DateUtilBase.stringFromDate(beforeDate,
					DateUtilBase.YEAR_MONTH_DAY);

			mCenterTitleDateTextView.setText(DateUtilBase.stringFromDate(
					beforeDate, "yyyy年MM月dd日"));
		} else if (tag == 1) {
			// 后一天
			Date afterDate = DateUtilBase.addDateOfDay(currentDate, 1);
			mCurrentDateString = DateUtilBase.stringFromDate(afterDate,
					DateUtilBase.YEAR_MONTH_DAY);

			mCenterTitleDateTextView.setText(DateUtilBase.stringFromDate(
					afterDate, "yyyy年MM月dd日"));
		} else {
			Date date = DateUtilBase.dateFromString(mCurrentDateString,
					DateUtilBase.YEAR_MONTH_DAY);
			mCenterTitleDateTextView.setText(DateUtilBase.stringFromDate(date,
					"yyyy年MM月dd日"));
		}

		updateLaterDayVisible(mCurrentDateString);

		updateData(false);

		// todo
		String uid = MyApplication.getInstance().getLoginInfo().UserID;
		int count = PhotoItem.getPhotosByDateCount(uid, mCurrentDateString);
		if (count == 0) {
			requestDownload();
		}
	}

	private void jumpCamera()
	{
		PermissionUtil.getInstance().request(getActivity(), new String[]{Manifest.permission.CAMERA,
						Manifest.permission.READ_EXTERNAL_STORAGE,
						Manifest.permission.WRITE_EXTERNAL_STORAGE},
				new PermissionResultCallBack() {
					@Override
					public void onPermissionGranted() {
						//
						String temp = SdLocal.getTempPhotoPath(getActivity(),
								"temp_camera_icon");
						UploadMenuImage.getInstance(FragmentGrow.this).setFilePath(temp);
						UploadMenuImage.getInstance(FragmentGrow.this).setIsCut(false);
						UploadMenuImage.getInstance(FragmentGrow.this).setIsPhotoDouble(true);

						int selectCount = 0;
						if (mModifyImageView != null) {
							selectCount = 1;
						} else {
							int size = mDataList != null ? mDataList.size() : 0;
							selectCount = PHOTO_COUNT_MAX - size;
						}

						UploadMenuImage.getInstance(FragmentGrow.this).setPhotoDoubleNum(selectCount);
						UploadMenuImage.getInstance(FragmentGrow.this).showPopAddPhoto();
					}

					@Override
					public void onPermissionGranted(String... permissions) {
						if (permissions == null || permissions.length == 0) {
						}
					}

					@Override
					public void onPermissionDenied(String... permissions) {
						if (permissions != null) {

						}
					}

					@Override
					public void onRationalShow(String... permissions) {
						if (permissions != null) {
							UIHelper.showToast(getActivity(), R.string.permission_tip);
							PermissionUtil.openSettingActivity(getActivity());
						}
					}
				});
	}


	public void showPopAddPhoto() {
		jumpCamera();
	}

	public void saveImageData() {

		// 必须重新获取,由于云端同步成功后，可能同步状态已经改变，但是没有刷新数据。
		ArrayList<PhotoItem> dataList = PhotoItem.getPhotosByDate(MyApplication
				.getInstance().getLoginInfo().UserID, mCurrentDateString);
		int size = dataList != null ? dataList.size() : 0;
		if (size > 0) {
			for (int i = 0; i < size; i++) {

				PhotoItem photoItem = dataList.get(i);
				if (new File(photoItem.imagePath).exists()) {
					String itemEditTextTag = String
							.format("itemEditText_%d", i);
					EditText itemEditText = (EditText) mDataListView
							.findViewWithTag(itemEditTextTag);
					if (itemEditText != null) {
						String content = itemEditText.getText().toString();

						if (!photoItem.desc.equals(content)) {
							if (photoItem.sync == PhotoItem.UPDATE_YES) {
								photoItem.modifyState = PhotoItem.MODIFY_YES;
							} else {
								photoItem.modifyState = PhotoItem.MODIFY_NO;
							}

							photoItem.desc = content;
							photoItem.sync = PhotoItem.UPDATE_NO;
							PhotoItem.updatePhotoItem(photoItem);
						}
					}
				}
			}
		}
	}

	private void addPhotoItem(String tempFilePath, boolean isCamera) {
		if (!TextUtils.isEmpty(tempFilePath)) {

			String filePath = SdLocal.getAlbumUserPath(getActivity(),
					MyApplication.getInstance().getLoginInfo().UserID,
					String.valueOf(System.currentTimeMillis()));

			boolean flag = false;
			try {
				// tempBitmap = ImageCompressUtils.comp(tempBitmap);
				// ImageUtilBase.saveImageToSd(tempBitmap, filePath);
				ImageCompressUtils.CompressImageFile(tempFilePath, filePath);

				flag = true;
			} catch (Exception e) {
				e.printStackTrace();
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
			}

			if (!flag) {
				UIHelper.showToast(getActivity(), R.string.load_image_fail);
				return;
			}

			if (isCamera) {
				// 删除照相机临时文件
				File tempCameraFile = new File(tempFilePath);
				if (tempCameraFile.exists()) {
					tempCameraFile.delete();
				}
			}

			if (mModifyImageView != null) {
				// 修改图片
				mModifyImageView.setImageBitmap(ImageUtilBase
						.getBitmapSmall(filePath));

				int position = (Integer) mModifyImageView.getTag();

				File noUseFile = new File(mModifyPhotoItem.imagePath);
				if (noUseFile.exists()) {
					noUseFile.delete();
				}

				if (mModifyPhotoItem.sync == PhotoItem.UPDATE_YES) {
					mModifyPhotoItem.modifyState = PhotoItem.MODIFY_YES;
				} else {
					mModifyPhotoItem.modifyState = PhotoItem.MODIFY_NO;
				}

				mModifyPhotoItem.imagePath = filePath;
				mModifyPhotoItem.sync = PhotoItem.UPDATE_NO;

				PhotoItem.updatePhotoItem(mModifyPhotoItem);

				mDataList.get(position).modifyState = mModifyPhotoItem.modifyState;
				mDataList.get(position).imagePath = mModifyPhotoItem.imagePath;
				mDataList.get(position).sync = mModifyPhotoItem.sync;

				// 设置完图片，致空，为添加状态
				mModifyImageView = null;
				mModifyPhotoItem = null;
			} else {
				// 添加图片
				PhotoItem item = new PhotoItem();
				item.uid = MyApplication.getInstance().getLoginInfo().UserID;
				item.sync = PhotoItem.UPDATE_NO;
				item.addTime = mCurrentDateString;
				item.imagePath = filePath;
				item.desc = "";// test
				item.modifyState = PhotoItem.MODIFY_NO;

				PhotoItem.insertPhotoItem(item);
				// mDataList.add(item);
			}
		} else {
			UIHelper.showToast(getActivity(), R.string.load_image_fail);
		}
	}

	// ==========================================================================================================
	/*
	 * 第一次同步数据
	 */
	private void requestSyncAllData() {

		mFirstSyncData = true;

		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
		String url = Setting.getGrowSyncByTimeUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);

			params.put("PageIndex", 1);
			params.put("PageSize", 1000);
			params.put("LatestSyncTime", "");
		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(url, map, null, this, REQUEST_FIRST_SYNC_DATA,
				false);
	}

	private void showSyncAllDialog() {

		if (mFirstSyncDialog != null && mFirstSyncDialog.isShowing())
			return;

		int currentIndex = MainTabActivity.getInstance().getMainMenuSelected();
		if (currentIndex != 2)
			return;

		mFirstSyncDialog = new MyDialog(getActivity());

		View view = LayoutInflater.from(getActivity()).inflate(
				R.layout.grow_fragment_sync_all_dialog, null);

		Button syncButton = (Button) view.findViewById(R.id.syncButton);
		Button waitNotifyButton = (Button) view
				.findViewById(R.id.waitNotifyButton);
		Button noNotifyButton = (Button) view.findViewById(R.id.noNotifyButton);

		TextView messageTextView = (TextView) view
				.findViewById(R.id.messageTextView);

		String cancelDownloadIndex = UserConfig.getConfigString(getActivity(),
				Const.CONFIG_APP_FIRST_SYNC_DATA_CANCEL_INDEX, "");
		if (TextUtils.isEmpty(cancelDownloadIndex)) {
			int size = mPhotoItemNetList != null ? mPhotoItemNetList.size() : 0;
			messageTextView.setText(String.format(
					"您在云端有%d张照片，是否一次性将其同步到手机客户端?", size));
		} else {
			mDownloadImageFlag = Integer.parseInt(cancelDownloadIndex);
			messageTextView.setText("您上次的同步没有完成，是否继续同步?");
		}

		syncButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				mFirstSyncDialog.dismiss();

				// 设置第一次同步为false
				UserConfig.setConfig(getActivity(),
						Const.CONFIG_APP_FIRST_SYNC_DATA, false);
				initPhotoProgressLayout(true);
			}
		});
		waitNotifyButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				mFirstSyncDialog.dismiss();

				mFirstSyncData = false;
			}
		});
		noNotifyButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				mFirstSyncDialog.dismiss();
				UserConfig.setConfig(getActivity(),
						Const.CONFIG_APP_FIRST_SYNC_DATA_NO_NOTIFY, true);
			}
		});

		mFirstSyncDialog.addView(view).create(null);
		mFirstSyncDialog.setCancelable(false);
		mFirstSyncDialog.setCanceledOnTouchOutside(false);
		mFirstSyncDialog.showMyDialog();

	}

	private void initPhotoProgressLayout(final boolean cloudLocal) {

		mCloudLocal = cloudLocal;

		LinearLayout photoUpdateLayout = (LinearLayout) mMainView
				.findViewById(R.id.photoUpdateLayout);
		ImageView growCloudImageView = (ImageView) mMainView
				.findViewById(R.id.growCloudImageView);

		photoUpdateLayout.setVisibility(View.VISIBLE);
		TextView progressTextView = (TextView) mMainView
				.findViewById(R.id.progressTextView);

		ProgressBar updateProgressBar = (ProgressBar) mMainView
				.findViewById(R.id.updateProgressBar);
		updateProgressBar.setProgress(0);

		TextView cancelTextView = (TextView) mMainView
				.findViewById(R.id.cancelTextView);
		cancelTextView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				showCancelUpdateDialog();
			}
		});

		mIsUpdate = true;

		if (cloudLocal) {
			growCloudImageView.setImageResource(R.drawable.grow_cloud_local);
			progressTextView.setText(String.format("正在同步...(%d/%d)", 0,
					mPhotoItemNetList.size()));

			updateProgressBar.setMax(mPhotoItemNetList.size());

			startDownloadPhoto();

		} else {
			growCloudImageView.setImageResource(R.drawable.grow_local_cloud);

			// todo
			String uid = MyApplication.getInstance().getLoginInfo().UserID;
			int size = PhotoItem.getPhotosByDateNoUpdateCount(uid,
					mCurrentDateString);

			updateProgressBar.setMax(size);

			progressTextView.setText(String.format("正在同步...(%d/%d)", 0, size));
		}
	}

	private void startDownloadPhoto() {
		new Thread(new Runnable() {

			@Override
			public void run() {

				PhotoItemNet photoItemNet = mPhotoItemNetList
						.get(mDownloadImageFlag);
				String fileName = EncodeMD5.getMd5(photoItemNet.PhotoUrl);

				String filePath = SdLocal.getAlbumUserPath(getActivity(),
						MyApplication.getInstance().getLoginInfo().UserID,
						fileName);

				boolean flag = false;
				if (!new File(filePath).exists()) {
					flag = HttpRequest.downloadFile(photoItemNet.PhotoUrl,
							filePath);

					if (flag) {
						PhotoItem photoItem = new PhotoItem();
						photoItem.uid = MyApplication.getInstance()
								.getLoginInfo().UserID;
						photoItem.sync = PhotoItem.UPDATE_YES;
						photoItem.addTime = photoItemNet.TakePictureDate;
						photoItem.imagePath = filePath;
						photoItem.desc = photoItemNet.Description;
						photoItem.modifyState = PhotoItem.MODIFY_NO;
						photoItem.pictureId = UtilityBase
								.parseInt(photoItemNet.PhotoID);

						PhotoItem.insertPhotoItem(photoItem);
						LogUtilBase.LogD(null, "下载成功" + mDownloadImageFlag);
					} else {
						LogUtilBase.LogD(null, "下载失败" + mDownloadImageFlag);
					}
				} else {
					LogUtilBase.LogD(null, "第" + mDownloadImageFlag + "张图片已存在");
				}
				mHandler.sendEmptyMessage(MSG_SYNC_DATA);

			}
		}).start();
	}

	private void showCancelUpdateDialog() {

		mCancelDialog = new MyDialog(getActivity());

		View view = LayoutInflater.from(getActivity()).inflate(
				R.layout.grow_dowload_cancel_dialog, null);

		Button cancelButton = (Button) view.findViewById(R.id.cancelButton);
		Button quitButton = (Button) view.findViewById(R.id.quitButton);

		cancelButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				mCancelDialog.dismiss();

				mUpdateMessageTextView = null;
			}
		});

		quitButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				mCancelDialog.dismiss();

				mUpdateMessageTextView = null;
				updateQuit();
			}
		});

		mUpdateMessageTextView = (TextView) view
				.findViewById(R.id.messageTextView);

		if (mCloudLocal) {
			int size = mPhotoItemNetList.size() - mDownloadImageFlag;
			mUpdateMessageTextView.setText(String.format("还有%d张照片没有下载，确定现在退出?",
					size));
		} else {
			int size = GrowSavePhotoManager.getInstance().mDataList.size()
					- GrowSavePhotoManager.getInstance().mCurrentIndex;
			mUpdateMessageTextView.setText(String.format("还有%d张照片没有上传，确定现在退出?",
					size));
		}

		mCancelDialog.addView(view).create(null);
		mCancelDialog.setCancelable(false);
		mCancelDialog.setCanceledOnTouchOutside(false);
		mCancelDialog.showMyDialog();
	}

	public void updateQuit() {
		LogUtilBase.LogD(null, "FragmentGrow updateQuit=====>>" + mIsUpdate);
		// 如果还在同步中，点击退出，才操作
		// 有时，同步结束了，用户还没有关闭退出
		if (mIsUpdate) {
			mIsUpdate = false;

			if (mFragmentInstance == null)
				return;

			LinearLayout photoUpdateLayout = (LinearLayout) mMainView
					.findViewById(R.id.photoUpdateLayout);
			photoUpdateLayout.setVisibility(View.GONE);

			if (mCloudLocal) {

				if (mFirstSyncData) {
					// 记录取消下载的
					UserConfig.setConfig(getActivity(),
							Const.CONFIG_APP_FIRST_SYNC_DATA_CANCEL_INDEX,
							String.valueOf(mDownloadImageFlag));
				}

				// 更新当前页数据
				updateData(false);
			} else {
				// upload
				GrowSavePhotoManager.getInstance().destroy();
				mHandler.sendEmptyMessage(MSG_SAVE_UPLOAD_SUCCESS);
			}
		}
	}

	/*
	 * 下载数据
	 */
	private void requestDownload() {

		mFirstSyncData = false;
		mDownloadImageFlag = 0;

		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
		String url = Setting.getSyncToAppUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);

			params.put("SyncTime", mCurrentDateString);//
		} catch (Exception e) {
		}
		map.put("ht", params);

		MainTabActivity.getInstance().showProgressDialog();
		ApiClient.http_post_main(url, map, null, this, REQUEST_DOWNLOAD_DATA,
				false);
	}

	private void showDownloadDialog() {

		final MyDialog myDialog = new MyDialog(getActivity());

		View view = LayoutInflater.from(getActivity()).inflate(
				R.layout.grow_download_dialog, null);

		Button syncButton = (Button) view.findViewById(R.id.syncButton);
		Button noSyncButton = (Button) view.findViewById(R.id.noSyncButton);

		int size = mPhotoItemNetList != null ? mPhotoItemNetList.size() : 0;
		TextView messageTextView = (TextView) view
				.findViewById(R.id.messageTextView);
		messageTextView.setText(String.format("您这一天有%d张照片，是否同步到本地?", size));

		syncButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				myDialog.dismiss();

				initPhotoProgressLayout(true);
			}
		});

		noSyncButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				myDialog.dismiss();
			}
		});

		myDialog.addView(view).create(null);
		myDialog.setCancelable(false);
		myDialog.setCanceledOnTouchOutside(false);
		myDialog.showMyDialog();
	}

	/*
	 * 上传数据
	 */
	private void requestUpload() {

		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
		String url = Setting.getSyncToAppUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);

			params.put("SyncTime", mCurrentDateString);//
		} catch (Exception e) {
		}
		map.put("ht", params);

		MainTabActivity.getInstance().showProgressDialog();
		ApiClient.http_post_main(url, map, null, this, REQUEST_UPLOAD_DATA,
				false);
	}

	private void showUploadDialog() {

		final MyDialog myDialog = new MyDialog(getActivity());

		View view = LayoutInflater.from(getActivity()).inflate(
				R.layout.grow_upload_dialog, null);

		Button syncButton = (Button) view.findViewById(R.id.syncButton);
		Button noSyncButton = (Button) view.findViewById(R.id.noSyncButton);

		int size = mPhotoItemNetList != null ? mPhotoItemNetList.size() : 0;
		TextView messageTextView = (TextView) view
				.findViewById(R.id.messageTextView);
		messageTextView.setText(String.format(
				"您这一天还有%d张照片在云端，同步后本地照片将会覆盖云端已有照片，是否同步?", size));

		syncButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				myDialog.dismiss();

				startUploadData();
			}
		});

		noSyncButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				myDialog.dismiss();
			}
		});

		myDialog.addView(view).create(null);
		myDialog.setCancelable(false);
		myDialog.setCanceledOnTouchOutside(false);
		myDialog.showMyDialog();
	}

	private void startUploadData() {
		initPhotoProgressLayout(false);
		GrowSavePhotoManager.getInstance().init(mCurrentDateString);
		GrowSavePhotoManager.getInstance().uploadImageContent();
	}

	@SuppressLint("InflateParams")
	public void showUploadSuccessDialog() {

		final MyDialog myDialog = new MyDialog(getActivity());

		Button bottomMenuApplyPhotoButton = (Button) mMainView
				.findViewById(R.id.bottomMenuApplyPhotoButton);
		Button bottomMenuSavePhotoButton = (Button) mMainView
				.findViewById(R.id.bottomMenuSavePhotoButton);

		bottomMenuApplyPhotoButton.setVisibility(View.VISIBLE);
		bottomMenuSavePhotoButton.setVisibility(View.GONE);

		View view = LayoutInflater.from(getActivity()).inflate(
				R.layout.grow_upload_success_dialog, null);

		Button cancelButton = (Button) view.findViewById(R.id.cancelButton);
		Button applyButton = (Button) view.findViewById(R.id.applyButton);
		
		boolean flag = UserConfig.getConfigBoolean(
				MyApplication.getInstance(), mCurrentDateString, false);
		if (flag) {
			applyButton.setText("重新申请热门相册");
		} else {
			applyButton.setText("申请热门相册");
		}

		cancelButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				myDialog.dismiss();
			}
		});

		applyButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				myDialog.dismiss();

				Intent applyIntent = new Intent(getActivity(),
						GrowApplyPhotoActivity.class);
				applyIntent.putExtra("CurrentDateString", mCurrentDateString);
				MainTabActivity.getInstance().startActivity(applyIntent, true);
			}
		});

		myDialog.addView(view).create(null);
		myDialog.setCancelable(false);
		myDialog.setCanceledOnTouchOutside(false);
		myDialog.showMyDialog();
	}

	// ==================================================
	/*
	 * 添加完照片，调用这个方法
	 */

	// private void updateAddPhoto() {
	// // if (mDataAdapter != null) {
	// // mDataAdapter.notifyDataSetChanged();
	// // } else {
	// // mDataAdapter = new PhotoItemAdapter(getActivity(), mDataList);
	// // mDataListView.setAdapter(mDataAdapter);
	// // }
	//
	// if (mDataList != null && mDataList.size() >= PHOTO_COUNT_MAX) {
	// mAddPhotoTextView.setText("每天只能添加9张照片");
	// }
	// }

	public void onActivityResult(int requestCode, int resultCode,
			final Intent data) {
		// if (resultCode == Activity.RESULT_OK) {
		// if (requestCode == ADD_RESULT_CAMERA) {
		// Bundle bundle = data.getExtras();
		// Bitmap bitmap = (Bitmap) bundle.get("data");
		// addPhotoItem(bitmap);
		// } else if (requestCode == ADD_RESULT_PHOTO) {
		// Bitmap bitmap = ImageUtilBase.getBitmap(ImageUtilBase
		// .getAbsoluteImagePath(getActivity(), data.getData()));
		// addPhotoItem(bitmap);
		// }
		// }

		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == JUMP_CALENDAR_REQUEST_CODE) {

				String selected_date_string = data.getExtras().getString(
						"selected_date_string");

				mCurrentDateString = selected_date_string;
				updateDayData(2);

			} else {
				UploadMenuImage.getInstance(this).onActivityResult(
						new CallBack() {
							@Override
							public void callBackSuccess(Object obj) {
								super.callBackSuccess(obj);

								//有的手机强转异常
//								Uri uri = (Uri) obj;
//								if (uri.toString().startsWith("file")) {
//
//								}
								// camera
								String tempPath = SdLocal.getTempPhotoPath(
										getActivity(), "temp_camera_icon");

								dynamicUpdateAlbumCover();
								addPhotoItem(tempPath, true);
								updateData(true);
								updateAddPhotoTextView();
							}
						}, requestCode, resultCode, data);
			}
		}
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_FIRST_SYNC_DATA:

				if (mPhotoItemNetList != null && mPhotoItemNetList.size() > 0) {

					showSyncAllDialog();
				} else {
					// 如果云端没有数据，就设置为false
					UserConfig.setConfig(getActivity(),
							Const.CONFIG_APP_FIRST_SYNC_DATA, false);
				}
				break;
			case MSG_SYNC_DATA:

				if (mIsUpdate) {
					mDownloadImageFlag++;

					ProgressBar updateProgressBar = (ProgressBar) mMainView
							.findViewById(R.id.updateProgressBar);
					TextView progressTextView = (TextView) mMainView
							.findViewById(R.id.progressTextView);

					if (mDownloadImageFlag > mPhotoItemNetList.size() - 1) {
						// download finish
						UIHelper.showToast(getActivity(), "同步成功");

						updateProgressBar.setProgress(mDownloadImageFlag);
						progressTextView.setText(String.format(
								"正在同步...(%d/%d)", mDownloadImageFlag,
								mPhotoItemNetList.size()));

						if (mFirstSyncData) {
							UserConfig
									.setConfig(
											getActivity(),
											Const.CONFIG_APP_FIRST_SYNC_DATA_CANCEL_INDEX,
											"");
						}

						LinearLayout photoUpdateLayout = (LinearLayout) mMainView
								.findViewById(R.id.photoUpdateLayout);
						photoUpdateLayout.setVisibility(View.GONE);

						mIsUpdate = false;

						updateData(false);

						updateAlbumCover();
					} else {
						progressTextView.setText(String.format(
								"正在同步...(%d/%d)", mDownloadImageFlag + 1,
								mPhotoItemNetList.size()));

						updateProgressBar.setProgress(mDownloadImageFlag + 1);

						startDownloadPhoto();
					}

					// 取消dialog
					if (mUpdateMessageTextView != null) {
						int count = mPhotoItemNetList.size()
								- mDownloadImageFlag;
						mUpdateMessageTextView.setText(String.format(
								"还有%d张照片没有下载，确定现在退出?", count));

						if (count <= 0) {
							if (mCancelDialog != null) {
								mCancelDialog.dismiss();
							}
						}
					}
				}

				break;
			case MSG_UPLOAD_DATA:

				int index = msg.arg1;
				int size = msg.arg2;
				TextView progressTextView = (TextView) mMainView
						.findViewById(R.id.progressTextView);
				ProgressBar updateProgressBar = (ProgressBar) mMainView
						.findViewById(R.id.updateProgressBar);

				if (index > size - 1) {
					updateProgressBar.setProgress(index);
					progressTextView.setText(String.format("正在同步...(%d/%d)",
							index, size));
				} else {
					updateProgressBar.setProgress(index + 1);
					progressTextView.setText(String.format("正在同步...(%d/%d)",
							index + 1, size));
				}

				// 取消dialog
				if (mUpdateMessageTextView != null) {
					int count = size - index;
					mUpdateMessageTextView.setText(String.format(
							"还有%d张照片没有下载，确定现在退出?", count));

					if (count <= 0) {
						if (mCancelDialog != null) {
							mCancelDialog.dismiss();
						}
					}
				}

				break;
			case MSG_SAVE_UPLOAD_SUCCESS:

				LinearLayout photoUpdateLayout = (LinearLayout) mMainView
						.findViewById(R.id.photoUpdateLayout);
				photoUpdateLayout.setVisibility(View.GONE);

				mIsUpdate = false;
				break;
			case MSG_UPDATE_ALBUM_COVER:

				updateAlbumCover();
				updateAlbumCoverText();
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_SAVE_ALBUM_NAME)) {
			LogUtilBase.LogD(null, "save album name success");
		} else if (object.equals(REQUEST_FIRST_SYNC_DATA)) {

			mPhotoItemNetList = PhotoItemNet.parseJsonData((String) data);

			mHandler.sendEmptyMessage(MSG_FIRST_SYNC_DATA);
		} else if (object.equals(REQUEST_DOWNLOAD_DATA)) {
			MainTabActivity.getInstance().hideProgressDialog();

			mPhotoItemNetList = PhotoItemNet.parseJsonData((String) data);
			if (mPhotoItemNetList != null && mPhotoItemNetList.size() > 0) {

				if (mPhotoItemNetList.size() > FragmentGrow.PHOTO_COUNT_MAX) {
					ArrayList<PhotoItemNet> tempList = new ArrayList<PhotoItemNet>();
					for (int i = 0; i < PHOTO_COUNT_MAX; i++) {
						tempList.add(mPhotoItemNetList.get(i));
					}
					mPhotoItemNetList = tempList;
				}
				
				ArrayList<PhotoItemNet> tempList = new ArrayList<PhotoItemNet>();
				for(int i=mPhotoItemNetList.size()-1;i>=0;i--)
				{
					tempList.add(mPhotoItemNetList.get(i));
				}
				
				mPhotoItemNetList = tempList;
				showDownloadDialog();
			}
		} else if (object.equals(REQUEST_UPLOAD_DATA)) {
			MainTabActivity.getInstance().hideProgressDialog();

			mPhotoItemNetList = PhotoItemNet.parseJsonData((String) data);

			if (mPhotoItemNetList != null && mPhotoItemNetList.size() > 0) {
				showUploadDialog();
			} else {
				startUploadData();
			}
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_SAVE_ALBUM_NAME)) {
			LogUtilBase.LogD(null, "save album name fail");
		} else if (object.equals(REQUEST_FIRST_SYNC_DATA)) {

		} else if (object.equals(REQUEST_DOWNLOAD_DATA)) {
			MainTabActivity.getInstance().hideProgressDialog();
		} else if (object.equals(REQUEST_UPLOAD_DATA)) {
			MainTabActivity.getInstance().hideProgressDialog();
		}
	};

}
